<script setup lang="ts">
  import { getCommentTree, page, statusChange } from '@/api/comment.ts'
  import TableCustom from '@/components/common/TableCustom.vue'
  import TableSearch from '@/components/common/TableSearch.vue'
  import { BlogComment } from '@/types'
  import { FormOption, TableColumns } from '@/types/form-option.ts'
  import { Loading, View } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { reactive, ref } from 'vue'
  import dayjs from 'dayjs'

  import CommentTreeNode from '@/views/blog/blog-comment/components/CommentTreeNode.vue'
  import { CommentNode } from '@/types/comment'

  const param = reactive({
    keyword: '',
    status: undefined as number | undefined,
    reply: undefined as number | undefined,
    pageNum: 1,
    pageSize: 10,
  })
  const searchOpt = ref<FormOption[]>([
    {
      type: 'input',
      label: '关键词：',
      prop: 'keyword',
      placeholder: '搜索评论内容、昵称或邮箱',
    },
    {
      type: 'select',
      label: '状态：',
      prop: 'status',
      opts: [
        { value: '0', label: '初始' },
        { value: '1', label: '通过' },
        { value: '2', label: '拒绝' },
      ],
    },
    {
      type: 'select',
      label: '新回复',
      prop: 'reply',
      opts: [
        { value: '1', label: '有' },
        { value: '0', label: '无' },
      ],
    },
  ])

  const columns = ref<TableColumns[]>([
    { type: 'index', prop: '', label: '序号', width: 55, align: 'center' },
    { prop: 'blogTitle', label: '标题', width: 200 },
    { prop: 'nickname', label: '昵称' },
    { prop: 'ip', label: 'ip地址' },
    { prop: 'email', label: '邮箱' },
    { prop: 'content', label: '内容' },
    { prop: 'status', label: '状态' },
    { prop: 'replyCount', label: '回复数' },
    { prop: 'reply', label: '新回复' },
    {
      prop: 'operator',
      label: '操作',
      viewHidden: true,
      editHidden: true,
      deleteHidden: true,
    },
  ])
  const tableData = ref<BlogComment[]>([])

  const total = ref(0)

  // 递归为评论树每个节点添加 createTimeFormat 字段
  const transformCommentTree = (comment: BlogComment): CommentNode => {
    return {
      ...comment,
      createTimeFormat: dayjs(comment.createTime).format('YYYY-MM-DD HH:mm:ss'),
      children: comment.children?.map(transformCommentTree) || [],
    }
  }

  // 审核弹窗相关
  const auditDialogVisible = ref(false)
  const commentTree = ref<CommentNode | null>(null)
  const currentAuditComment = ref<BlogComment | null>(null)

  //查询分页
  const getData = async () => {
    const date = await page(param)
    tableData.value = date.records
    total.value = date.total
  }

  //搜索方法
  const handleSearch = () => {
    changePage(1)
  }

  const changePage = (val: number) => {
    param.pageNum = val
    getData()
  }

  // 打开审核弹窗
  const handleAudit = async (row: BlogComment) => {
    try {
      currentAuditComment.value = row
      // 获取评论树结构
      const tree = await getCommentTree({ id: row.id })
      commentTree.value = transformCommentTree(tree)
      auditDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取评论详情失败')
      console.error(error)
    }
  }

  // 在树状结构中处理审核操作
  const handleTreeAudit = async (commentId: string, status: number) => {
    try {
      await statusChange({ id: commentId, status })
      ElMessage.success('审核成功')
      // 重新获取评论树
      if (currentAuditComment.value) {
        const tree = await getCommentTree({ id: currentAuditComment.value.id })
        commentTree.value = transformCommentTree(tree)
      }
      // 刷新列表数据
      await getData()
    } catch (error) {
      ElMessage.error('审核失败')
      console.error(error)
    }
  }

  // 关闭审核弹窗
  const closeAuditDialog = () => {
    auditDialogVisible.value = false
    commentTree.value = null
    currentAuditComment.value = null
  }

  getData()
</script>

<template>
  <div>
    <!--  搜索栏  -->
    <TableSearch :query="param" :options="searchOpt" :search="handleSearch" />
    <TableCustom
      :columns="columns"
      :table-data="tableData"
      :total="total"
      :change-page="changePage"
      :current-page="param.pageNum"
      :page-size="param.pageSize"
    >
      <template #status="{ row }">
        <el-tag v-if="row.status == 0" type="info">初始</el-tag>
        <el-tag v-else-if="row.status == 1" type="success">通过</el-tag>
        <el-tag v-else-if="row.status == 2" type="danger">拒绝</el-tag>
      </template>
      <template #reply="{ row }">
        <el-tag v-if="row.reply === 0" type="info">无</el-tag>
        <el-tag v-if="row.reply === 1" type="danger">有</el-tag>
      </template>
      <template #operator="{ row }">
        <el-button type="primary" size="small" :icon="View" @click="handleAudit(row)">
          审核
        </el-button>
      </template>
    </TableCustom>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="评论审核"
      width="80%"
      :destroy-on-close="true"
      @close="closeAuditDialog"
    >
      <div v-if="commentTree" class="comment-tree-container">
        <div class="comment-tree">
          <CommentTreeNode
            :comment="commentTree"
            :on-audit="handleTreeAudit"
            :show-audit-buttons="true"
            :level="0"
          />
        </div>
      </div>
      <div v-else class="loading">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        加载中...
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .comment-tree-container {
    max-height: 60vh;
    overflow-y: auto;
    padding: 10px;
  }

  .loading {
    text-align: center;
    padding: 40px;
    color: #999;
  }
</style>
